﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace CloverNet.Authorization
{
    public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //跳过Authentication
            var skipAuthentication = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) ||
                                     filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

            if (skipAuthentication)
            {
                return;
            }

            //校验权限
            var valid = DefaultValidtorProvider.Current.ValidatePermission(filterContext.ActionDescriptor);

            if (!valid)
            {
                filterContext.Result = AuthorizationManager.UnAuthenticationAction?.Invoke(filterContext.HttpContext) ?? new HttpUnauthorizedResult();
            }
        }
    }
}
